package com.dk.uaa.service;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.uaa.mapper.SysAdminMapper;
import com.dk.uaa.mapper.SysPermissionMapper;
import com.dk.uaa.po.SysAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * Security验证
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private SysAdminMapper sysAdminMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SysAdmin> queryWrapper = null;
        // 从数据库查询到用户
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_name",username);
        SysAdmin sysAdmin = sysAdminMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(sysAdmin)){
            // 返回的对象交给Provider去处理，返回的不是userDetails，Provider就会抛异常
            return null;
        }
        // 根据用户id查询到对应的权限

        String[] permission = sysPermissionMapper.selectPermissionByAdminId(sysAdmin.getAdminId());
        // 将用户的信息给userDetails对象
        // 因为我们的密码编码器使用的是BCrypt,所以需要我们数据库中的密码必须符合他的编码规范，通过BCrypt.hashpw("dk",BCrypt.gensalt())将我们的密码加密,第二个参数是随机盐

        // 扩展用户信息，存入对象的json数据内容作为username的内容,在资源服务器中获取可封装到对象中
        String password = sysAdmin.getPassword();
        sysAdmin.setPassword("");

        return User.withUsername(JSON.toJSONString(sysAdmin)).password(password).authorities(permission).build();
    }
}
